package de.farbstreich.tozen2.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;


public class ClientSocket {

	Socket socket;
	BufferedWriter outputStream;
	ClientSocketInputThread inputThread;
	boolean socketIsSet = false;
	private GameData gameData;
	public  ClientGUI gui;
	private ClientPingThread pingThread;
	
	public ClientSocket(GameData gameData, ClientGUI gui) {
		this.gameData = gameData;
		this.gui = gui;
	}
	
	public boolean startSocket(String socketAddress, int port) {
		try {
			socket = new Socket(socketAddress, port);
			outputStream = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()));
			inputThread = new ClientSocketInputThread(new BufferedReader( new InputStreamReader( socket.getInputStream() ) ), gameData, gui);
			pingThread = new ClientPingThread( this );
			inputThread.start();
			pingThread.start();
			socketIsSet = true;
		} catch (IOException e) {
			this.closeSocket();
			System.err.println(e.toString());
		}
		return socketIsSet;
	}
	
	public void closeSocket() {
		gui.frame.changePanel(gui.frame.getLoginPanel());
		try {
			inputThread.close();
			outputStream.close();
			socket.close();
		} catch (IOException e) {
			System.err.println(e.toString());
			System.exit(1);
		}
	}

	public boolean isSet() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
}
